package cc.magicjson.synthesis.decorator;



import cc.magicjson.synthesis.model.Coupon;
import cc.magicjson.synthesis.model.Order;
import cc.magicjson.synthesis.model.User;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.Optional;

/**
 * 优惠券折扣装饰器，为订单添加优惠券折扣信息
 */
public class CouponDiscountDecorator extends OrderDiscountDecorator {
    private Coupon usedCoupon; // 使用的优惠券
    private BigDecimal discountAmount; // 折扣金额

    public CouponDiscountDecorator(Order order) {
        super(order);
        this.discountAmount = BigDecimal.ZERO;
    }

    @Override
    public Order applyDiscount() {
        if (!order.isUseCoupon()) {
            return order; // 不使用优惠券折扣
        }

        User user = order.getUser();

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 找出最优惠的券（折扣金额最大的），且满足条件：未使用、在有效期内、订单金额满足使用条件
        Optional<Coupon> bestCoupon = user.getCoupons().stream()
                .filter(coupon -> !coupon.isUsed())
                .filter(coupon -> now.isAfter(coupon.getStartTime()) && now.isBefore(coupon.getEndTime()))
                .filter(coupon -> order.getFinalAmount().compareTo(coupon.getThresholdAmount()) >= 0)
                .max(Comparator.comparing(Coupon::getDiscountAmount));

        if (bestCoupon.isPresent()) {
            this.usedCoupon = bestCoupon.get();
            this.discountAmount = usedCoupon.getDiscountAmount();

            // 确保折扣后金额不小于0
            this.discountAmount = this.discountAmount.min(order.getFinalAmount());

            // 更新订单金额
            BigDecimal newFinalAmount = order.getFinalAmount().subtract(this.discountAmount);
            order.setFinalAmount(newFinalAmount);

            // 更新订单总折扣金额
            BigDecimal newDiscountAmount = order.getDiscountAmount().add(this.discountAmount);
            order.setDiscountAmount(newDiscountAmount);
        }

        return order;
    }

    @Override
    public String getDiscountDescription() {
        if (usedCoupon != null) {
            return "使用优惠券「" + usedCoupon.getName() + "」抵扣" + discountAmount + "元";
        }
        return "未使用优惠券折扣";
    }

    @Override
    public BigDecimal getDiscountAmount() {
        return discountAmount;
    }

    public Coupon getUsedCoupon() {
        return usedCoupon;
    }
}
